package com.ysd.gulimall.auth.controller;

import ch.qos.logback.core.net.SyslogOutputStream;
import com.alibaba.fastjson.TypeReference;
import com.ysd.common.utils.R;
import com.ysd.common.vo.MemberRespVo;
import com.ysd.gulimall.auth.component.SmsComponent;
import com.ysd.gulimall.auth.feign.MemberFeignService;
import com.ysd.gulimall.auth.vo.UserLoginVo;
import com.ysd.gulimall.auth.vo.UserRegistVo;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.stream.Collectors;

@Controller
public class LoginController {

    @Autowired
    SmsComponent smsComponent;

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    MemberFeignService memberFeignService;

    @ResponseBody
    @GetMapping("/sms/sendcode")
    public R sendCode(@RequestParam("phone") String phone) {

        String redisCode = redisTemplate.opsForValue().get("sms:code:" + phone);
        if (redisCode!= null){
            long l = Long.parseLong(redisCode.split("_")[1]);
            if (System.currentTimeMillis() - l < 60000){
                return R.error("已有验证码");
            }
        }
        smsComponent.sendSms(phone);
        return R.ok();
    }

    @PostMapping("/regist")
    public String regist (@Valid UserRegistVo vo, BindingResult result, RedirectAttributes redirectAttributes){
        if (result.hasErrors()) {
            //把验证不通过的错误信息封装到map
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage, (s, a) -> s + a));
            //把错误信息返回到页面
            redirectAttributes.addFlashAttribute("errors", errors);
            //校验出错，转发到注册页
            return "redirect:http://127.0.0.1:12000/reg.html";
        }
        //页面传来的验证码
        String code = vo.getCode();
        //从redis里读取的验证码
        String redisCode = redisTemplate.opsForValue().get("sms:code:" + vo.getPhone());

        if (!StringUtils.isEmpty(redisCode)){
            if (code.equals(redisCode.split("_")[0])){
                //从redis里删除验证码
                redisTemplate.delete("sms:code:"+vo.getPhone());
                System.out.println("auth:"+vo);
                R r = memberFeignService.regist(vo);
                if (r.getCode() == 0){
                    return "redirect:/login.html";
                }else{
                    Map<String, String> errors = new HashMap<>();
                    errors.put("msg", "注册失败");
                    redirectAttributes.addFlashAttribute("errors", errors);
                    return "redirect:http://127.0.0.1:12000/reg.html";
                }
            }else{
                Map<String, String> errors = new HashMap<>();
                errors.put("code", "验证码错误");
                redirectAttributes.addFlashAttribute("errors", errors);
                return "redirect:http://127.0.0.1:12000/reg.html";
            }
        }else{
            Map<String, String> errors = new HashMap<>();
            errors.put("code", "验证码错误");
            redirectAttributes.addFlashAttribute("errors", errors);
            return "redirect:http://127.0.0.1:12000/reg.html";
        }
    }


    @PostMapping("/login")
    public String login(UserLoginVo vo, RedirectAttributes redirectAttributes, HttpSession session){

        //远程登录
        R login = memberFeignService.login(vo);

        if (login.getCode() == 0){
            MemberRespVo data = login.getData("data", new TypeReference<MemberRespVo>() {
            });
            System.out.println("密码登录：L"+data);
            session.setAttribute("loginUser", data);
            return "redirect:http://localhost:10000/";
        }else {
            Map<String, String> errors = new HashMap<>();
            errors.put("msg", "账号密码错误");
            redirectAttributes.addFlashAttribute("errors",errors);
            return "redirect:/login.html";
        }
    }

}
